<?php

namespace Qy\Controller;

use Common\Controller\BaseController;

/**
 *  个人信息
 *  @author zangyilei
 */

class TopicController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        if (empty($this->iUserId)) {
            $this->error("请登录!", -103);
        }    
    }
    
    /**
     *  获取店铺信息并发送验证码
     */
    public function sendCode(){
        $strCustomer = $this->getParam('customer', '', 'string', true);

        //查询用户
        $userPhone = D('User')->where(array('user_id'=>$this->iUserId))->getField('phone');
        
        //获取CRM账号
        $customerInfo = $this->getCrmCustomer($strCustomer,$userPhone);
   
        //查询发送次数
        $this->authSendCode($customerInfo['phone']);
        //店铺信息存入缓存
        $this->setCacheByCustomer($strCustomer, $customerInfo);
        
        $phone = substr_replace($customerInfo['phone'],'****',3,4);
        $this->success("已发送验证码到（".$phone."）",1);
    }
    
    /**
     *  验证码验证
     *  1、验证码是否正确
     *  2、绑定店铺ID
     */
    public function checkCustomer(){
        
        $customer       = $this->getParam('customer', '', 'string', true);
        $verifyCode     = $this->getParam('verifyCode', '', 'int', true);
        $customerInfo   = $this->getCacheByCustomer($customer);
        if (! $customerInfo) $this->error('请重新获取验证码');
        $customerCode   = $this->getCacheByCustomer($customerInfo['phone']);
 
        //验证验证码是否正确
        if($verifyCode != $customerCode) $this->error('验证码错误');
        // 存入缓存
        $customerInfo['code'] = $verifyCode;
        $this->setCacheByCustomer($customer, $customerInfo);
        //查询是否关联店铺,未关联，增加关联信息
        $this->relatCustomer($customer);
        
        $this->success('验证成功');
    }

    /**
     *  报名信息提交      
     *
     */
    Public function apply(){
        $data = $this->getData();
        $customer   = $this->getParam('customer', '', 'string', true);
        $userPhone = D('User')->where(array('user_id'=>$this->iUserId))->getField('phone');
        $customerInfo = $this->getCacheByCustomer($customer);
        if (!$customerInfo) $this->error('店铺信息不匹配');
     
        // 报名信息提交CRM
        $data['customer_id']= $customerInfo['customer_id'];
        $data['phone']      = $data['phone'];
        $data['source']     = 2;
        $data['sign']       = $this->getSign($data);
        $res = $this->pushCrmApplyInfo($data);
        if ($res){// 创建支付定单
            $htmlData = $this->alipay($data);
            header('Content-Type:text/html; charset=utf-8');
            exit($htmlData);
//             $this->success('报名成功','',array('data'=>$htmlData));
        }
    }
    
    /**
     * 2.省份/市
     * @param int $level 
     * @param int $upid
     * @return list
     */
    public function area() {
        $level     = $this->getParam('level','','int',true);
        $upid      = $this->getParam('upid','','int',true);
        
        $where = array();
        $where['level'] = $level;
        $where['upid'] = $upid;
        $data = M('District')->field('id,name')->where($where)->select();

        return $this->returnList($data);
    }
    
    //支付宝支付
    protected function alipay($data) {
        import("Alipay.AliPay");
        $objAlipay                     = new \AliPay();
        $objAlipay->orderid            = $this->createOrderNo(); //订单号
        $objAlipay->subject            = '网商云学院报名';//商品名称
        $objAlipay->price              = '6000.00';//金额
//         $objAlipay->isMobile           = $data['phone'];
    
        $objAlipay->notify_url         = C('ALIPAY_NOTIFY_URL');//服务器异步通知页面路径
        $objAlipay->return_url         = C('ALIPAY_RETURN_URL');//页面跳转同步通知页面路径

        return $objAlipay->pay(C('ALIPAY_CONFIG_TBVIP'));
    }
    
    /**
     * 报名信息提交CRM
     * @param unknown $applyInfo
     */
    protected function pushCrmApplyInfo($applyInfo)
    {
        $custonerInfo = array();
        // 请求CRM接口
        $response = do_get_request(C('HTTP_HOST_CRM') . '/index.php?s=Api/Index/outerApply', $applyInfo);
        $response = json_decode($response, true);
        if ($response['success'])
        {
            return true;
        } else
        {
            $message = $response['message'] ? $response['message'] : '报名失败';
            $this->error($message);
        }
    }
    
    /**
     * 创建支付定单
     * @param unknown $payment
     */
    protected function createPayment($payment){
        return $this->add($payment, 'Payment', true);
    }
    
    /**
     * 获取CRM账号
     * @param unknown $customer
     * @param int $userPhone
     */
    protected function getCrmCustomer($strCustomer,$userPhone){
        $custonerInfo = array();
        $params['customer'] = $strCustomer;
        $params['phone']    = $userPhone;
        $params['source']   = 2;
        $params['sign'] = $this->getSign($params);
     
        // 请求CRM接口
        $response = do_get_request(C('HTTP_HOST_CRM') . '/index.php?s=Api/Index/getIdByName', $params);
        $response = json_decode($response, true);
        $custonerInfo = $response['data'];
        
        return $custonerInfo;
    }
    
    protected function getCacheByCustomer($customer)
    {
        $customerStr = S($customer . '_customer');
        return json_decode($customerStr, true);
    }
    
    protected function setCacheByCustomer($customer, $customerInfo)
    {
        return S($customer . '_customer', json_encode($customerInfo));
    }
    
    /**
     * 更新企业关联店铺
     * @param unknown $customer
     */
    protected function relatCustomer($customer){
        $Relat = D('UserCompanyRelat');
        
        $data['customer_id'] = $customer;
        $Relat->where(array('user_id'=>$this->iUserId))->save($data);
    }
    
    /**
     * 检测并发送验证码
     * @param int $phone
     */
    protected function authSendCode($phone){
        $strRand    = createVerify($phone . '_customer');
        $strMessage = "【网商云学院】验证码：{$strRand}，用于活动报名和绑定店铺，请注意使用安全";
        
        //查询发送日志
        $logArr = $this->getYzmLog($phone);
        
        if($logArr['num'] >= 5){
            $this->error('您今天发送验证码到上限，明天再来吧!');
        }elseif ($logArr['num'] > 0 && $logArr['num'] < 5){ 
            $res = $this->setLogInc($logArr['id']);
        }else { //创建新用户
            $res = $this->addYzmLog($phone,$strMessage);
        }
        
        if ($res){
            sys_sms($phone,$strMessage);            
        }else {
            $this->error("发送失败");
        }
      
    }

    /**
     * 添加发送验证码信息
     * @param int $id
     */
    protected function addYzmLog($phone,$message){
        $YzmLog = D('YzmLog');
        
        $YzmLog->phone          = $phone;
        $YzmLog->code           = $message;
        $YzmLog->num            = 1;
        $YzmLog->type           = 1;
        $YzmLog->create_time    = format_time();
        $result                 = $YzmLog->add();
       return $result;
    }
    
    /**
     * 获取发送验证码详情
     * @param String $phone
     */
    protected function getYzmLog($phone) {
        $data = D('YzmLog')
            ->field('id,num')
            ->where("create_time >= date(now()) and create_time < DATE_ADD(date(now()),INTERVAL 1 DAY)")
            ->where(array('type'=>1 ,'phone'=>$phone))
            ->find();
        
        return $data;
    }
    
    /**
     * 更新验证码次数
     * @param int $id
     */
    protected function setLogInc($id){
        $result = D('YzmLog')->where(array(id=>$id))->setInc('num',1);
        return $result;
    }
    
    /**
     * 获取签名
     * @param array $data
     */
    protected function getSign($data){
        ksort($data);
        $postStr = http_build_query($data);
        $sign     = md5($postStr . C('API_ENCRYPT_KEY'));
        
        return $sign;
    }
    
    protected function createOrderNo()
    {
        return date("Ymd") . (int) (microtime(true) * 10) . mt_rand(1000, 9999);
    }
    
    /**
     * 验证数据
     * @param unknown $customer
     */
    protected function getData() {
        $data               = array();
        $data['company']    = $this->getParam("company",'','string',true,'公司名称不能为空');
        $data['phone']      = $this->getParam("phone",'','string',true, '联系号码不可为空');
        $data['phone']      = $this->getParam("phone",'',C('PATTERN_MOBILE'),true,'联系号码格式不正确');
        $data['actor']      = $this->getParam("actor",'','string',true, '联系人不可为空');
        $data['ww']         = $this->getParam("ww",'','string',true, '联系旺旺不能为空');
        $data['email']      = $this->getParam("email",'','string',true, '联系邮箱不能为空');
        $data['email']      = $this->getParam("email",'',C('PATTERN_EMAIL'),true, '邮箱格式不正确');
        $data['province']   = $this->getParam("province",'','string',true, '省份不能为空');
        $data['city']       = $this->getParam("city",'','string',true, '城市不能为空');
    
        return $data;
    }
    
}